package edu.sjtu.grid.workflow.iterator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import edu.sjtu.grid.workflow.Util;
import edu.sjtu.grid.workflow.graph.Graph;
import edu.sjtu.grid.workflow.graph.Node;

public class UpwardRankIterator implements GraphIterator{

	private Graph graph = null;
	
	private Node nodeList[] = null;
	private List<Integer> nodeIndex = null;
	private int size = 0;
	private int currentI = 0;
	//private Integer savedI = null;
	
	public UpwardRankIterator(Graph graph)
	{
		this.graph = graph;
		
		this.nodeList = this.graph.getNodeList();
		this.size = this.nodeList.length;
		this.nodeIndex = new ArrayList<Integer>();
		for(int i=0; i< size; i++)
			this.nodeIndex.add(i);
		
		Collections.sort(this.nodeIndex, new UpwardRankComparator(this.nodeList));
	}
	
	@Override
	public boolean hasNext() {
		return this.currentI < this.size;
	}

	@Override
	public Node next() {
		return this.nodeList[this.nodeIndex.get(this.currentI++)];
	}
	
	@Override
	public boolean hasBefore() {
		return this.currentI > 0;
	}

	@Override
	public Node before() {
		return this.nodeList[this.nodeIndex.get(--this.currentI)];
	}
	
	/*@Override
	public void save() {
		this.savedI = this.currentI;
	}

	@Override
	public boolean resume() {
		if(this.savedI == null)
			return false;
		this.currentI = this.savedI;
		this.savedI = null;
		return true;
	}
	
	@Override
	public int getDepth()
	{
		return this.currentI;
	}*/

	private class UpwardRankComparator implements Comparator<Integer>{
		private Node nodeList[] = null;
		public UpwardRankComparator(Node nodeList[])
		{
			this.nodeList = nodeList;
		}
		@Override
		public int compare(Integer arg0, Integer arg1) {
			Node node0 = this.nodeList[arg0];
			Node node1 = this.nodeList[arg1];
			double rank0 = node0.getUpwardRank();
			double rank1 = node1.getUpwardRank();
			if(Util.isSmall(rank0, rank1))
				return 1;
			else
				return -1;
		}
	}



	
}
